package com.nanmeishu.infrastructure.datasource.config;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import lombok.RequiredArgsConstructor;
import lombok.experimental.var;
import org.apache.ibatis.logging.nologging.NoLoggingImpl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Configuration
@RequiredArgsConstructor
@EnableTransactionManagement
@MapperScan("com.nanmeishu.services.**.mapper")
@ConditionalOnClass(value = {PaginationInterceptor.class})
public class MybatisPlusConfig {


    private final MybatisPlusProperties mybatisPlusProperties;
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

    @PostConstruct
    public void initMybatisConfig(){
        mybatisPlusProperties.setMapperLocations(new String[]{"classpath*:/mapper/*Mapper.xml"});
        mybatisPlusProperties.setTypeAliasesPackage("com.nanmeishu.services.*.entity");

        MybatisConfiguration configuration = mybatisPlusProperties.getConfiguration();
        if(Objects.isNull(configuration)){
            configuration=new MybatisConfiguration();
        }
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(true);
        configuration.setLogImpl(NoLoggingImpl.class);
        mybatisPlusProperties.setConfiguration(configuration);

        var globalConfig = mybatisPlusProperties.getGlobalConfig();
        if(Objects.isNull(globalConfig)){
            globalConfig=new GlobalConfig();
        }
        GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
        if(Objects.isNull(dbConfig)){
            dbConfig=new GlobalConfig.DbConfig();
        }
        configuration.setCallSettersOnNulls(true);
        dbConfig.setIdType(IdType.ASSIGN_ID);
        dbConfig.setTableUnderline(true);
        dbConfig.setLogicDeleteValue("1");
        dbConfig.setLogicNotDeleteValue("0");
        dbConfig.setLogicDeleteField("def_flag");
        globalConfig.setDbConfig(dbConfig);
        globalConfig.setBanner(false);
    }
}